import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { resetRouter } from '@/routers';
import { loginApi, logoutApi, emailLoginApi, refreshTokenApi, qqLoginApi } from '@/api/auth';
import { getUserInfoApi } from '@/api/user';
import { QQLoginData, EmailLoginData, LoginData } from '@/api/auth/types';
import { useCommentStore } from '@/store/modules/comment';
import { useTokenExpiredStore } from './tokenExpired';
import { store } from '@/store';

/**
 * 用户状态管理 Store (组合式API写法)
 * 管理用户登录状态、token、用户信息、角色权限等
 */
export const useUserStore = defineStore(
  'userState',
  () => {
    // ==================== State 状态 ====================

    /** 登录token */
    const token = ref('');

    /** 路由权限签名（基于 roles/perms 的稳定签名，用于触发路由重建） */
    const routeSignature = computed(() => {
      // 只有在 roles 或 perms 数组长度为 0 时才触发重新计算
      if (!roles.value || roles.value.length === 0) {
        return 'empty-roles';
      }

      // 使用 roles 作为主要标识，简化签名逻辑
      const sortedRoles = [...roles.value].sort().join(',');
      return `roles:${sortedRoles}`;
    });

    /** 登录用户信息 */
    const userInfo = ref({
      id: 0,
      username: '',
      avatar: '',
      description: ''
    });

    /** 用户角色 */
    const roles = ref(localStorage.roles ? JSON.parse(localStorage.roles) : []);

    /** 用户权限 */
    const perms = ref(localStorage.perms ? JSON.parse(localStorage.perms) : []);

    // ==================== Actions 操作 ====================
    /**
     * 游客登录
     * 设置游客角色权限和默认用户信息
     */
    const loginByGuest = () => {
      const commentStore = useCommentStore();
      roles.value = ['GUEST'];
      localStorage.roles = JSON.stringify(roles.value);
      token.value = '';
      userInfo.value = {
        id: 288,
        username: '匿名用户',
        avatar: 'http://www.monkeyk.fun/bucket-test-1/public/image/Guest.png',
        description: '先登录，再编辑个人简介'
      };
      commentStore.resetCommentState();
    };

    /**
     * 判断是否已登录
     * @returns {boolean} 是否已登录
     */
    const isLogin = () => !!token.value;

    /**
     * 判断角色是否为游客
     * @returns {boolean} 是否为游客角色
     */
    const isGuest = () => roles.value.includes('GUEST');

    /**
     * 用户登录
     * @param {LoginData} userInfo - 登录信息
     * @returns {Promise} 登录结果
     */
    const login = (userInfo: LoginData) => {
      const { username } = userInfo;
      return new Promise(async (resolve, reject) => {
        loginApi(userInfo)
          .then(async response => {
            const { tokenType, accessToken } = response.data;
            token.value = `${tokenType} ${accessToken}`; // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
            await getUserInfo();
            // 普通页面登录，由token过期store处理重定向
            const tokenExpiredStore = useTokenExpiredStore();
            if (!tokenExpiredStore.isTokenDialogShowing) {
              tokenExpiredStore.redirectAfterLogin();
            }
            resolve(username);
          })
          .catch(error => {
            reject(error);
          });
      });
    };

    /**
     * 邮箱登录
     * @param {EmailLoginData} emailInfo - 邮箱登录信息
     * @returns {Promise} 登录结果
     */
    const emailLogin = (emailInfo: EmailLoginData) => {
      const { email } = emailInfo;
      return new Promise(async (resolve, reject) => {
        emailLoginApi(emailInfo)
          .then(async response => {
            const { tokenType, accessToken } = response.data;
            token.value = `${tokenType} ${accessToken}`; // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
            await getUserInfo();
            // 普通页面登录，由token过期store处理重定向
            const tokenExpiredStore = useTokenExpiredStore();
            if (!tokenExpiredStore.isTokenDialogShowing) {
              tokenExpiredStore.redirectAfterLogin();
            }
            resolve(email);
          })
          .catch(error => {
            reject(error);
          });
      });
    };

    /**
     * 第三方QQ登录
     * @param {QQLoginData} qqInfo - QQ登录信息
     * @returns {Promise} 登录结果
     */
    const loginWithQQ = (qqInfo: QQLoginData) => {
      const { userInfo: qqUserInfo } = qqInfo;
      return new Promise(async (resolve, reject) => {
        qqLoginApi(qqInfo)
          .then(async response => {
            const { tokenType, accessToken } = response.data;
            token.value = `${tokenType} ${accessToken}`; // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
            await getUserInfo();
            // 普通页面登录，由token过期store处理重定向
            const tokenExpiredStore = useTokenExpiredStore();
            if (!tokenExpiredStore.isTokenDialogShowing) {
              tokenExpiredStore.redirectAfterLogin();
            }
            resolve(qqUserInfo);
          })
          .catch(error => {
            reject(error);
          });
      });
    };

    /**
     * 获取用户信息
     * 通过token请求接口获取用户详细信息
     * @returns {Promise} 用户信息
     */
    const getUserInfo = () =>
      new Promise((resolve, reject) => {
        getUserInfoApi()
          .then(({ data }) => {
            if (!data) {
              reject('Verification failed, please Login again.');
              return;
            }
            if (!data.roles || data.roles.length <= 0) {
              reject('getUserInfo: roles must be a non-null array!');
              return;
            }
            userInfo.value = {
              id: data.userId || 0,
              username: data.nickname || '',
              avatar: data.avatar || '',
              description: data.description || ''
            };
            roles.value = data.roles;
            perms.value = data.perms;
            localStorage.roles = JSON.stringify(roles.value);
            localStorage.perms = JSON.stringify(perms.value);
            resolve(data);
          })
          .catch(error => {
            reject(error);
          });
      });

    /**
     * 设置用户角色信息
     * @param {Array} newRoles - 新的角色数组
     * @returns {Promise} 设置结果
     */
    const getInfo = (newRoles: []) =>
      new Promise(resolve => {
        roles.value = newRoles;
        resolve(newRoles);
      });

    /**
     * 用户退出登录
     * 清除token、用户信息、角色权限，并重新加载页面
     * @returns {Promise} 退出结果
     */
    const logout = () =>
      new Promise((resolve, reject) => {
        const commentStore = useCommentStore();
        logoutApi()
          .then(() => {
            // 清理用户状态
            token.value = '';
            userInfo.value = {
              id: 0,
              username: '',
              avatar: '',
              description: ''
            };
            roles.value = [];
            perms.value = [];

            // 清理 localStorage
            localStorage.removeItem('roles');
            localStorage.removeItem('perms');

            // 重置其他相关状态
            commentStore.resetCommentState();
            const tokenExpiredStore = useTokenExpiredStore();
            tokenExpiredStore.reset();

            // 重置路由 - 使用resetRouter而不是location.reload
            resetRouter();

            resolve(null);
          })
          .catch(error => {
            reject(error);
          });
      });

    /**
     * 重置token
     * 清除token并重置路由
     * @returns {Promise} 重置结果
     */
    const resetToken = () =>
      new Promise(resolve => {
        token.value = '';
        resetRouter();
        // 角色清空导致权限变化
        roles.value = [];
        resolve(null);
      });

    /**
     * 设置登录结果（用于第三方登录直接设置登录状态）
     * @param {Object} loginResult - 登录结果
     * @returns {Promise} 设置结果
     */
    const setLoginResult = (loginResult: any) =>
      new Promise(async (resolve, reject) => {
        try {
          // 设置token
          if (loginResult.accessToken) {
            token.value = `Bearer ${loginResult.accessToken}`;
          }

          // 设置用户信息
          if (loginResult.userInfo) {
            userInfo.value = {
              id: loginResult.userInfo.userId || 0,
              username: loginResult.userInfo.nickname || loginResult.userInfo.username || '',
              avatar: loginResult.userInfo.avatar || '',
              description: loginResult.userInfo.description || ''
            };

            // 设置角色和权限
            if (loginResult.userInfo.roles) {
              roles.value = loginResult.userInfo.roles;
              localStorage.roles = JSON.stringify(roles.value);
            }

            if (loginResult.userInfo.permissions) {
              perms.value = loginResult.userInfo.permissions;
              localStorage.perms = JSON.stringify(perms.value);
            }
          }

          // 普通页面登录，由token过期store处理重定向
          const tokenExpiredStore = useTokenExpiredStore();
          if (!tokenExpiredStore.isTokenDialogShowing) {
            tokenExpiredStore.redirectAfterLogin();
          }

          resolve(loginResult);
        } catch (error) {
          reject(error);
        }
      });

    /**
     * 刷新用户token
     * 使用refreshToken获取新的accessToken
     * @returns {Promise} 刷新结果
     */
    const refreshUserToken = () =>
      new Promise((resolve, reject) => {
        refreshTokenApi()
          .then(response => {
            const { tokenType, accessToken } = response.data;
            token.value = `${tokenType} ${accessToken}`;
            resolve(token.value);
          })
          .catch(error => {
            reject(error);
          });
      });

    // 返回所有state和actions
    return {
      token,
      userInfo,
      roles,
      perms,
      routeSignature,
      loginByGuest,
      isLogin,
      isGuest,
      login,
      emailLogin,
      loginWithQQ,
      setLoginResult,
      getUserInfo,
      getInfo,
      logout,
      resetToken,
      refreshUserToken
    };
  },
  {
    // 进行持久化存储
    persist: {
      // 本地存储的名称
      key: 'userState',
      // 保存的位置
      storage: window.localStorage // localstorage
    }
  }
);

/**
 * 非setup环境使用的用户store hook
 * 用于在非setup环境中访问用户store
 * @returns {Object} 用户store实例
 */
export function useUserStoreHook() {
  return useUserStore(store);
}
